<?php

if(!defined('OI')) {
			
	print '<h1>Access Error</h1>Sorry, this file can not be accessed directly, this is strictly forbidden!';
	exit();
				
}

class Modules {

	# Store digitalUniversity
	private $digitalUniversity = NULL;

	/*
	 * Constructor: Store instance of sitebuilder
	 * 	- PHP5 now uses pass by reference so we do not need to store the reference
	*/
	public function __construct(DigitalUniversity &$digitalUniversity) {
	
		$this->digitalUniversity =& $digitalUniversity;
				
	}
	
	/*
	 * Destructor: Clean memory parts
	*/
	public function __destruct() {
		
		unset($this->digitalUniversity);
		
	}
	
	/*
	 * fixHTMLTags: Takes a given HTML string and renders the output into formatted XHTML.
	 * The input does not need to be valid HTML, so it fixes invalid HTML (retrieved from external sourceS)
	 *
	 * @param $html - The HTML input
	 * @return string - Cleaned HTML output
	*/
	private function fixHTMLTags($html) {
		
		$doc = new DOMDocument();
		@$doc->loadHTML($html);
		$html = $doc->saveHTML();		
		unset($doc);
		
		$html = trim(preg_replace('#(.*)<body>(.*)</body>(.*)#', '\2', $html));
				
		return $html;
		
	} 
	
	/*
	 * extractContent: Given a module, retrieve the external content and extract the 
	 * relevant parts of the page that are of interest. Loop through the page 
	 * contents to get a break down of each section.
	 *
	 * @param &$module - Reference to a module array
	 * @return array - details that are stored in the database 
	*/
	private function extractContent(&$module) {
			
		# Page details
		$fetchURL = 'http://www.csc.liv.ac.uk/teaching/modules/year'.$module['year'].'s'.$module['semester'].'/full-'.strtolower($module['code']).'.html';
							
		$ch = curl_init();			
			curl_setopt($ch, CURLOPT_URL, $fetchURL);
			curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
			curl_setopt($ch, CURLOPT_TIMEOUT, 3);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		$pageResults = curl_exec($ch);												
		curl_close($ch);
								
		# Did we get any data?
		if(!empty($pageResults)) {
																	
			# Define variables
			$fullDetails = array();
			$matches = array();
						
			preg_match('#<div id=\''.$module['code'].'\'>(.*?)<\/div>#siu', $pageResults, $matches);
						
			# Store result
			$pageResults = $matches[1];
						
			# Get the details container
			$detailsText = array();
			preg_match('#<\/h1>(.*?)<h2>#siu', $pageResults, $detailsText);
			
			# Get all the details
			$detailsTemp = array();			
			preg_match_all('#<b>(.*?):<\/b> (.*?)<br>#siu', $detailsText[1], $detailsTemp);

			# Store details
			foreach($detailsTemp[1] as $k => $v) {
				$v = strtolower(str_replace(' ', '_', $v));
				if($v == 'member_of_staff_with_responsibility_for_the_module') {
					$v = 'staff_member';
				} elseif($v == 'originating_department') {
					$v = 'department';
				}
				$fullDetails['overview'][$v] = $detailsTemp[2][$k];	
			}
			
			# Clean memory
			unset($detailsTemp, $detailsText);
			
			# Strip tags
			$pageResults = $this->fixHTMLTags($pageResults);
			$pageResults = strip_tags($pageResults, '<h2><h3><b><a><p><li><ul><ol><strong><em><br>');
			
			# Other sections
			preg_match_all('#<h2>([a-zA-Z_\-\s]*)<\/h2>(.(<p>(.*?)<\/p>|<ol>(.*?)</ol>|<ul>(.*?)<\/ul>|([a-zA-Z0-9_\-:\s]*))*)#siu', $pageResults, $pageDetails);
			
			# Clean output
			if(!empty($pageDetails[1])) {
			
				foreach($pageDetails[1] as $k => $v) {
				
					$v = strtolower(str_replace(array(' ', "\n"), array('_', ''), $v));
					$text = preg_replace('!\s+!', ' ', str_replace(array("\n"), array(''), $pageDetails[2][$k]));
					$fullDetails[$v] = $text;
					
				}
				
			}
												
		}
		
		if(!empty($fullDetails)) {
		
			# Clean output
			foreach($fullDetails as $k => $v) {
			
				if(!is_array($v)) {
					
					$fullDetails[$k] = $this->safeString($v);
						
				} else {
				
					foreach($v as $ck => $cv) {
					
						$fullDetails[$k][$ck] = $this->safeString($cv);
						
					}
					
				}
				
			}
		
			# Serialize				
			$compressedDetails = json_encode($fullDetails);
		
			# Update table
			$this->digitalUniversity->db->query("UPDATE modules SET details = '{$compressedDetails}' WHERE moduleID = '{$module['moduleID']}' LIMIT 1");
			
		}
		
		# Return our array
		return $fullDetails;
		
	}
	
	/*
	 * safeString: Convert the string to HTML entities, cleaning empty tags 
	 * and multiple whitespace (for valid JSON)
	 *
	 * @param $string - The string to render
	 * @return string - The rendered string
	*/
	private function safeString($string) {
	
		$string = preg_replace('/\s+/', ' ', $string);
		$string = preg_replace('#<p[^>]*>(\s|&nbsp;?)*</p>#', '', $string);
		$string = str_replace('<br><br>', '', $string);
		$string = addslashes(htmlentities($string, ENT_QUOTES, 'UTF-8'));
		
		return $string;
		
	}
	
	/*
	 * nonSafeString: Convert the HTML entities into its original format.
	 *
	 * @param $string - The string to render
	 * @return string - The rendered string
	*/
	public static function nonSafeString($string) {
	
		return html_entity_decode($string, ENT_QUOTES, 'UTF-8');
		
	}
	
	/*
	 * mapSafetyString: Given an array, map the array to the given callback
	 * calling the method on each element in the array (and sub-elements)
	 *
	 * @param &$array - Reference to the array
	 * @param $callback - The callback method
	 *
	 * @return array - The new array once processed
	*/
	private function mapSafetyString(&$array, $callback) {
		
		$new = array();
		
		# Do we have array?
		if(is_array($array)) {
			foreach ($array as $key => $val) {
				if (is_array($val)) {
					$new[$key] = $this->mapSafetyString($val, $callback);
				} else {
					$new[$key] = call_user_func($callback, $val);
				}
			}
		} else {
			$new = call_user_func($callback, $array);
		}
		
		return $new;
		
	}
	
	/*
	 * getModule: Query the database for the current module.
	 *
	 * @return array - Details of the module
	*/
	private function getModule() {
		
		# Particular module
		$module = $this->digitalUniversity->db->getRow("SELECT * FROM modules
		WHERE moduleID = '{$this->digitalUniversity->input['module']}' OR code = '{$this->digitalUniversity->input['module']}'
		LIMIT 1");
		
		return $module;
		
	}
	
	/*
	 * getModuleNotes: Query the database for the current module notes
	 *
	 * @param &$moduleID - An integer reference value
	 * @param $limit - The amount of notes to return
	 *
	 * @return array - Array of module notes
	*/
	private function getModuleNotes(&$moduleID, $limit = 8) {
		
		$moduleNotes = $this->digitalUniversity->db->getResults("SELECT * FROM modules_notes
		WHERE moduleID = '{$moduleID}'
		LIMIT 8");
		
		return $moduleNotes;
			
	}
	
	/*
	 * getModuleResources: Query the database for the current module resources
	 *
	 * @param &$moduleID - An integer reference value
	 * @param $limit - The amount of resources to return
	 * @param $isApproved - Get approved resources or pending
	 *
	 * @return array - Array of resource objects (books, links, etc)
	*/
	private function getModuleResources(&$moduleID, $limit = 8, $isApproved = 1) {
		
		# Get resources
		$moduleResources = $this->digitalUniversity->db->getResults("SELECT r.resourceID, NULL, r.title, r.type, r.isReported, r.isApproved, r.location, r.time FROM modules_resources mr
		LEFT JOIN resources r ON (r.resourceID = mr.resourceID)
		WHERE mr.moduleID = '{$moduleID}' AND r.isApproved = '{$isApproved}'
		
		".($isApproved ? "UNION DISTINCT
		
		SELECT b.ISBN, b.copies, b.title, 'book' AS type, b.cacheTime, b.available, b.description, b.cacheTime AS time FROM modules_books mb
		LEFT JOIN books b ON (mb.ISBN = b.ISBN)
		WHERE mb.moduleID = '{$moduleID}'" : '')."
		
		LIMIT {$limit}");
				
		return $moduleResources;
			
	}
		
	private function moduleAssessments(&$moduleID) {
	
		# Get assessments
		$moduleAssessments = $this->digitalUniversity->db->getResults("SELECT * FROM modules_assessment
		WHERE moduleID = '{$moduleID}'
		ORDER BY deadline ASC");
		
		# Define variables
		$assessmentID = array();
		$assessments = array();
		$ownAssessments = array();
		$totalMark = 0;
		$currentMark = 0;
		
		# Extract IDs	
		if(!empty($moduleAssessments)) {
				
			foreach($moduleAssessments as $k => $v) {
			
				$assessmentID[] = $v['assessmentID'];
				$assessments[$v['assessmentID']] =& $moduleAssessments[$k];
				$totalMark += $v['worth'];
				
			}
			
			# User marks
			$userAssessments = $this->digitalUniversity->db->getResults("SELECT * FROM users_assessment 
			WHERE userID = '{$this->digitalUniversity->user['userID']}' AND assessmentID IN('".implode("', '", $assessmentID)."')
			ORDER BY assessmentID ASC");
			
			# Does the user have any?
			if(!empty($userAssessments)) {
				
				# Store by assessmentID
				foreach($userAssessments as $k => $v) {
			
					$ownAssessments[$v['assessmentID']] = $v;
					$ownAssessments[$v['assessmentID']]['mark'] = ($v['score'] / $assessments[$v['assessmentID']]['mark']) * $assessments[$v['assessmentID']]['worth'];
					$currentMark += $ownAssessments[$v['assessmentID']]['mark'];
										
				}
				
				# Free memory
				unset($userAssessments);
			
			}
							
		}	
		
		# Round numbers
		if($currentMark != 0) {
			$currentMark = round($currentMark, 1);
		}
	
		echo '<section class="contentBlock">';
			
			if(!empty($moduleAssessments)) {
				
				echo '<div class="moduleProgress">
					<div class="percentage">'.$currentMark.'%</div>
					<div class="text">of final grade achieved</div>
					<div class="ratingBar">
						<div class="grey" style="width: '.$totalMark.'%;"></div>
						<div class="green" style="width: '.$currentMark.'%;"></div>
					</div>
				</div>';
				
				foreach($moduleAssessments as $k => $v) {
				
					if(!empty($ownAssessments[$v['assessmentID']])) {
						$mark = $ownAssessments[$v['assessmentID']]['mark'];
					} else {
						$mark = 0;	
					}
				
					echo '<div class="assignment">
						<h1>'.$v['title'].'</h1>
						<div class="assignment_worth">Worth: '.$v['worth'].'%</div>
						<div class="assignment_due">Due: '.$this->digitalUniversity->dateTimer('due', $v['deadline']).'</div>
						<div class="assignment_grade">'.$mark.'%</div>
					</div>';
					
				}
				
			} else {
				
				echo '<p>There are no assessments available at this time.</p>';	
				
			}
			
		echo '</section>';	
		
	}
	
	private function saveResource() {
		
		# Get current module
		$module = $this->getModule();
		
		# No module, redirect
		if(empty($module)) {
			
			return $this->digitalUniversity->redirect('modules');
			
		}
		
		# File upload or URL
		if($this->digitalUniversity->post['type'] == 'webpage') {
			
			$fileName = $this->digitalUniversity->post['location'];
			
		} else {
		
			# Define variables
			$dateFolder = date('Y').'/'.date('m').'-'.date('d').'/'.date('H').'/';
			$uploadDirectory = ROOT_PATH.'uploads/'.$dateFolder;
			
			# Create directory
			if(!is_dir($uploadDirectory)) {
				mkdir($uploadDirectory, 0777, true);
			}
		
			# Get uploader
			include_once(SOURCE_PATH.'class/Upload.php');
						
			# Create upload instance
			$uploader = new Upload($_FILES['resourceFile'], $uploadDirectory);
							
			# Extensions allowed
			$uploader->setExtensions(array(".doc", ".docx", ".ppt", ".pptx", ".pdf")); 
			
			# Process upload
			$results = $uploader->upload();
			
			# Any errors?
			if($results['error'] == true) {
				
				# Redirect
				return $this->digitalUniversity->redirect('modules&module='.$module['code'].'&act=error&message='.serialize($results));
				
			} else {
				
				$fileName = $dateFolder.$results['filename'];
				
			}

		}
		
		# Define variables
		$time = time();
										
		# Insert resource
		$this->digitalUniversity->db->query("INSERT INTO resources SET title = '{$this->digitalUniversity->post['title']}', type = '{$this->digitalUniversity->post['type']}', isReported = 0, isApproved = 0, location = '{$fileName}', time = '{$time}'");
		$resourceID = $this->digitalUniversity->db->insertID;
				
		# Insert module resource
		$this->digitalUniversity->db->query("INSERT INTO modules_resources SET resourceID = '{$resourceID}', moduleID = '{$module['moduleID']}'");
				
		# Insert user resource
		$this->digitalUniversity->db->query("INSERT INTO users_resources SET resourceID = '{$resourceID}', userID = '{$this->digitalUniversity->user['userID']}'");
		
		# Redirect
		return $this->digitalUniversity->redirect('modules&module='.$module['code'].'&act=saved');
		
	}
	
	/*
	 * moduleAnnouncements: Retrieve the module announcements from the database
	 * and output them.
	 *
	 * @param &$moduleID - Reference to an integer value
	 *
	*/
	private function moduleAnnouncements(&$moduleID) {
	
		# Get announcements
		$moduleAnnouncements = $this->digitalUniversity->db->getResults("SELECT * FROM modules_news
		WHERE moduleID = '{$moduleID}'
		ORDER BY time DESC
		LIMIT 3");
	
		# Output module announcements
		echo '<h4>Announcements</h4>
		<section class="contentBlock">';
		
			# Do we have any?
			if(!empty($moduleAnnouncements)) {
				
				# Loop through each
				foreach($moduleAnnouncements as $k => $v) {
					echo '<article class="announcement'.((($k + 1) % 3 == 0) ? ' announcementLastChild' : '').'">
						<p>'.$v['title'].'</p>
					</article>';
				}
				
			# No announcements to display
			} else {
				
				echo '<p>There are no announcements.</p>';	
				
			}
		
		echo '</section>';
		
	}
	
	/*
	 * addResource: Display the add resource block
	 *
	 * @param &$moduleID - Reference to an integer value
	 * @param &$moduleTitle - Reference to a string title
	*/
	private function addResource(&$moduleID, &$moduleTitle) {
		
		echo '<h4>Add Resource</h4>
		<section class="contentBlock">
			<p class="uploadResource">Add a resource to <em>"'.$moduleTitle.'"</em> for other students to use.</p>
			<a class="upload" href="'.$this->digitalUniversity->config['scripturl'].'page=modules&module='.$moduleID.'&view=new">Upload</a>
		</section>';

	}
	
	/*
	 * showModuleSide: Output the module side contents.
	 *
	 * @param &$module - An array reference to a module
	*/
	private function showModuleSide(&$module) {
		
		echo '<section class="rightColumn">';		

			# Display announcements
			if(!empty($module)) {
				$this->moduleAnnouncements($module['moduleID']);
				$this->addResource($module['code'], $module['title']);
			}
		
		echo '</section>';
		
	}
	
	/*
	 * viewModuleResources: Display all the module resources.
	 *
	*/
	private function viewModuleResources() {
		
		# Get current module
		$module = $this->getModule();
		
		# Get all resources
		if(!empty($module)) {
		
			# Page tree
			$this->digitalUniversity->addPageTree($module['code'].(!empty($module['title']) ? ': '.$module['title'] : ''), $this->digitalUniversity->config['scripturl'].'page=modules&module='.$module['code']);
			$this->digitalUniversity->addPageTree('Resources', $this->digitalUniversity->config['scripturl'].'page=modules&module='.$module['code'].'&view=resources');
			
			# Get resources
			$moduleResources = $this->getModuleResources($module['moduleID'], 40);
			
			# Get lecture notes
			$moduleNotes = $this->getModuleNotes($module['moduleID'], 30);
			
		}
		
		echo '<section class="leftColumn">
			<h1>'.(!empty($module['title']) ? $module['code'].': '.$module['title'] : 'Module').'</h1>
			<nav class="pageTab">
				<a class="focus" href="#" data-tab="resources">Resources</a>
				<a href="#" data-tab="notes">Lecture Notes</a>
			</nav>			
			
			<section id="tab_resources" class="dataTab">	';
			
			# Define variable
			$noResources = false;
			
			if(!empty($module)) {
				
				if(!empty($moduleResources)) {
									
					echo '<!-- Open: fileFilter -->
					<section class="fileFilter" id="fileFilter">
						<a href="'.$this->digitalUniversity->config['scripturl'].'page=modules&module='.$module['code'].'&view=resources#all" data-type="all">All files</a>
						<a href="'.$this->digitalUniversity->config['scripturl'].'page=modules&module='.$module['code'].'&view=resources#books" data-type="book">Books</a>
						<a href="'.$this->digitalUniversity->config['scripturl'].'page=modules&module='.$module['code'].'&view=resources#word" data-type="word">Word</a>
						<a href="'.$this->digitalUniversity->config['scripturl'].'page=modules&module='.$module['code'].'&view=resources#pdf" data-type="pdf">PDF</a>
						<a href="'.$this->digitalUniversity->config['scripturl'].'page=modules&module='.$module['code'].'&view=resources#powerpoint" data-type="powerpoint">Powerpoint</a>
						<a href="'.$this->digitalUniversity->config['scripturl'].'page=modules&module='.$module['code'].'&view=resources#webpage" class="lastChild" data-type="webpage">Web Page</a>
					</section>
					<!-- Close: fileFilter -->
					
					<p id="noResources" class="hidden">There are no resources matching this filter.</p>
					
					<section class="contentBlock clearfix">';
											
					foreach($moduleResources as $k => $v) {
				
						if($v['type'] == 'book') {
							$link = 	$this->digitalUniversity->config['scripturl'].'page=books&book='.$v['resourceID'];
						} else {
							$link = 	$this->digitalUniversity->config['scripturl'].'page=resources&resource='.$v['resourceID'];
						}
						
						if($v['type'] == 'webpage') {
							$saveLink = $v['location'];
						} else {
							$saveLink = $this->digitalUniversity->config['root_url'].'uploads/'.$v['location'];
						}
				
						echo '<article class="document '.$v['type'].'">							
							<h5 class="title">'.$v['title'].'</h5>
							'.(($v['type'] != 'book') ? '<div class="documentControlContainer">
								<div class="dialog documentControl">
									<a class="save" href="'.$saveLink.'" target="_blank">Save</a>
									<a class="open" href="'.$link.'">Open</a>
								</div>
							</div>' : '').'
						</article>';
						
					}
																						 
					echo '</section>';
					
				} else {
				
					$noResources = true;
					
				}
				
			} else {
				
				$noResources = true;
				
			}
			
			# Empty output
			if($noResources) {
				
				echo '<p>There are currently no resouces available.</p>';	
				
			}
			
			echo '</section>
			
			<section id="tab_notes" class="dataTab hidden">';
			
			# Define variable
			$noNotes = false;
			
			# Did we find a module?
			if(!empty($module)) {
				
				# Any module notes
				if(!empty($moduleNotes)) {
									
					echo '<section class="contentBlock clearfix">';
											
					foreach($moduleNotes as $k => $v) {
							
						echo '<article class="document pdf">							
							<h5 class="title">'.$v['title'].'</h5>
						</article>';
								
					}
																						 
					echo '</section>';
					
				} else {
					
					$noNotes = true;
					
				}
				
			} else {
				
				$noNotes = true;
				
			}
			
			# Empty output
			if($noNotes) {				
				
				echo '<p>There are currently no notes available.</p>';	
				
			}
			
			echo '</section>			
		</section>';
			
		
		# Output side details
		$this->showModuleSide($module);
		
	}
	
	private function addNewResource() {
		
		# Get current module
		$module = $this->getModule();
		
		# Get all resources
		if(!empty($module)) {
		
			# Page tree
			$this->digitalUniversity->addPageTree($module['code'].(!empty($module['title']) ? ': '.$module['title'] : ''), $this->digitalUniversity->config['scripturl'].'page=modules&module='.$module['code']);
			$this->digitalUniversity->addPageTree('Add Resource', $this->digitalUniversity->config['scripturl'].'page=modules&module='.$module['code'].'&view=new');
						
		} else {
			
			return $this->digitalUniversity->redirect('modules');
			
		}
		
		# Add Javascript loader
		$this->digitalUniversity->javascriptLoader('DigitialUniversity.addNewResource()');
		
		echo '<section class="fullPageWidth">
			<h1>'.$module['code'].': '.$module['title'].'</h1>
			<nav class="pageTab">
				<a class="focus" href="#" data-tab="home">Add Resource</a>								
				<a class="right" href="'.$this->digitalUniversity->config['scripturl'].'page=modules&module='.$module['code'].'&view=all" data-tab="notabber">Resources</a>
			</nav>
			<section class="contentBlock addNewResource" id="addNewResource">
				<form action="'.$this->digitalUniversity->config['scripturl'].'page=modules&module='.$module['code'].'" method="post" enctype="multipart/form-data">
				<ul>
					<li>
						<label for="type">Type:</label>
						<select name="type" id="type">
							<option value="word">Word Document</option>
							<option value="powerpoint">Powerpoint</option>
							<option value="pdf">PDF</option>
							<option value="webpage">Webpage Link</option>
						</select>
					</li>
					<li>
						<label for="title">Title:</label>
						<input type="text" name="title" id="title" value="" />
					</li>
					<li class="fileField">
						<label for="file">File:</label>
						<input type="file" name="resourceFile" id="file" />
					</li>
					<li class="webPageField hidden">
						<label for="location">Web URL:</label>
						<input type="text" name="location" id="location" value="http://" />
					</li>
					<li>
						<input type="submit" name="save" value="Add Resource" />
					</li>
				</ul>
				</form>				
			</section>
		</section>';
		
	}
	
	private function adminModule(&$module) {
		
		# Get pending resources
		$pendingResources = $this->getModuleResources($module['moduleID'], 20, 0);
		
		# Possible marks
		$assignmentValueSelect = '';
		for($i = 100; $i >= 1; $i--) {
			$assignmentValueSelect .= '<option value="'.$i.'">'.$i.'</option>';
		}
			
		# Deadline hour
		$assignmentHours = '';
		for($i = 9; $i <= 19; $i++) {
			$assignmentHours .= '<option value="'.$i.'"'.($i == 15 ? ' selected="selected"' : '').'>'.$i.'</option>';
		}
				
		# Deadline day
		$assignmentDays = '';
		$currentDay = date('d');
		for($i = 1; $i <= 31; $i++) {
			if($i < 10) {
				$i = '0'.$i;
			}
			$assignmentDays .= '<option value="'.$i.'"'.($i == $currentDay ? ' selected="selected"' : '').'>'.$i.'</option>';
		}
		
		# Deadline month		
		$assignmentMonth = '';
		$currentMonth = date('m');
		for($i = 1; $i <= 12; $i++) {
			if($i < 10) {
				$i = '0'.$i;
			}
			$assignmentMonth .= '<option value="'.$i.'"'.($i == $currentMonth ? ' selected="selected"' : '').'>'.$i.'</option>';
		}
			
		# Deadline year
		$assignmentYear = '';
		for($i = date('Y'); $i <= date('Y') + 1; $i++) {
			$assignmentYear .= '<option value="'.$i.'">'.$i.'</option>';
		}
			
		echo '<!-- Open:tab_administrate -->
		<section id="tab_administrate" class="dataTab hidden">
					
			<section class="contentBlock clearfix addNewResource">
				<h2>New Announcement</h2>
				<form action="'.$this->digitalUniversity->config['scripturl'].'page=modules&module='.$module['code'].'" method="post">
					<p class="noUpper">
						<label name="title">Title:</label> <input type="text" value="" name="title" />
					</p>
					<input type="submit" class="submitButton" name="addAnnouncement" value="Add Announcement" />
				</form>	
			</section>
					
			<section class="contentBlock clearfix addNewResource">
				<h2>New Lecture Notes</h2>
				<form action="'.$this->digitalUniversity->config['scripturl'].'page=modules&module='.$module['code'].'" method="post" enctype="multipart/form-data">
					<p class="noUpper">
						<label name="title">Title:</label> <input type="text" value="" name="title" />
					</p>
					<p class="fileField">
						<label for="file">File:</label>
						<input type="file" name="lectureNotes" id="file" />
					</p>
					<input type="submit" class="submitButton" name="addLectureNotes" value="Add Lecture Notes" />
				</form>	
			</section>
				
			<section class="contentBlock clearfix addNewResource">
				<h2>New Assignment</h2>
				<form action="'.$this->digitalUniversity->config['scripturl'].'page=modules&module='.$module['code'].'" method="post" enctype="multipart/form-data">
					<p class="noUpper">
						<label>Title:</label> 
						<input type="text" value="" name="title" />
					</p>
					<p class="fileField">
						<label for="worth">Worth (%):</label>
						<select name="worth" id="worth">'.$assignmentValueSelect.'</select>
					</p>
					<p class="fileField">
						<label for="marks">Marks (raw):</label>
						<select name="marks" id="marks">'.$assignmentValueSelect.'</select>
					</p>
					<p class="fileField">
						<label for="addAnnouncement">Announcement:</label>
						<input type="checkbox" id="addAnnouncement" name="autoAddAnnouncement" /> <div class="checkboxText">Automatically add a module announcement?</div>
					</p>
					<p class="fileField">
						<label>Deadline:<br />Hour Day Month Year</label>
						<select name="hour">'.$assignmentHours.'</select>
						<select name="day">'.$assignmentDays.'</select>
						<select name="month">'.$assignmentMonth.'</select>
						<select name="year">'.$assignmentYear.'</select>
					</p>
					<input type="submit" class="submitButton" name="addAssignment" value="Add Assignment" />
				</form>	
			</section>
					
			<section class="contentBlock clearfix">
				<h2>Pending Resources</h2>';
				if(!empty($pendingResources)) {
					echo '<form action="'.$this->digitalUniversity->config['scripturl'].'page=modules&module='.$module['code'].'" method="post">';
					foreach($pendingResources as $k => $v) {
						if($v['type'] == 'webpage') {
							$link = $v['location'];
						} else {
							$link = $this->digitalUniversity->config['root_url'].'uploads/'.$v['location'];
						}
						echo '<p class="noUpper">
							<input type="checkbox" name="approveResourceID[]" value="'.$v['resourceID'].'" /> '.ucfirst($v['type']).' - '.$v['title'].' [ <a href="'.$link.'" target="_blank">Verify Contents</a> ]									
						</p>';	
					}
					echo '<input type="submit" class="submitButton" name="approveResources" value="Approve" />
					</form>';
				} else {
					echo '<p>There are no resources pending approval</p>';
				}
			echo '</section>
					
		</section>
		<!-- Close:tab_administrate -->';
				
	}
	
	/* 
	 * showModule: Display a particular module page. This will include callbacks
	 * for the module details (if present, used from database otherwise extracted
	 * from the resource website) and all side content.
	 *
	*/
	private function showModule() {
		
		# Define state
		$canAdministrate = false;
		
		# Admins can do all
		if($this->digitalUniversity->user['groupLevel'] == 4) {
			$canAdministrate = true;
		}
		
		# Get current module
		$module = $this->getModule();
		
		# Get all resources
		if(!empty($module)) {
		
			# Page tree
			$this->digitalUniversity->addPageTree($module['code'].(!empty($module['title']) ? ': '.$module['title'] : ''), $this->digitalUniversity->config['scripturl'].'page=modules&module='.$module['code']);
		
			if(empty($module['details'])) {
				
				$moduleDetails = $this->extractContent($module);
								
			} else {
				
				$moduleDetails = json_decode(stripslashes($module['details']), true);
								
			}
			
			$moduleDetails = $this->mapSafetyString($moduleDetails, array('Modules', 'nonSafeString'));
											
			# Get lecture notes
			$moduleNotes = $this->getModuleNotes($module['moduleID'], 8);
									
			# Get resources
			$moduleResources = $this->getModuleResources($module['moduleID'], 8);
			
			# Lecturer of module
			if(($this->digitalUniversity->user['groupLevel'] == 3) && ($module['lecturer'] == $this->digitalUniversity->user['userID'])) {
				$canAdministrate = true;
			}
						
		}	
		
		/* 
		 * If we can administrate, we need to check for new announcements, lecture material and any resources being approved.
		 *
		*/
		if($canAdministrate) {
		
			# New announcement
			if(isset($this->digitalUniversity->post['addAnnouncement'])) {
				
				if(!empty($this->digitalUniversity->post['title'])) {
				
					$time = time();	
					
					# Insert announcement			
					$this->digitalUniversity->db->query("INSERT INTO modules_news SET moduleID = '{$module['moduleID']}', title = '{$this->digitalUniversity->post['title']}', status = '1', time = '{$time}'");	
					
					# Send out notification
					$this->digitalUniversity->db->query("UPDATE users SET notifications = (notifications + 1) 
					WHERE userID IN (
						SELECT userID FROM users_modules WHERE moduleID = '{$module['moduleID']}'
					)");
					
					# Redirect
					return $this->digitalUniversity->redirect('modules&module='.$module['code'].'&act=saved&message=Your announcement has been added');
					
				}
				
			# Approve resources
			} elseif(isset($this->digitalUniversity->post['approveResources'])) {
			
				if(!empty($this->digitalUniversity->post['approveResourceID'])) {
									
					# Insert announcement			
					$this->digitalUniversity->db->query("UPDATE resources SET isApproved = '1' WHERE resourceID IN('".implode("', '", $this->digitalUniversity->post['approveResourceID'])."')");	
										
					# Redirect
					return $this->digitalUniversity->redirect('modules&module='.$module['code'].'&act=saved&message=The selected resources have been approved');
					
				}
				
			# Add new lecture notes
			} elseif(isset($this->digitalUniversity->post['addLectureNotes'])) {
			
				# Define variables
				$dateFolder = date('Y').'/'.date('m').'-'.date('d').'/'.date('H').'/';
				$uploadDirectory = ROOT_PATH.'uploads/'.$dateFolder;
				
				# Create directory
				if(!is_dir($uploadDirectory)) {
					mkdir($uploadDirectory, 0777, true);
				}
			
				# Get uploader
				include_once(SOURCE_PATH.'class/Upload.php');
							
				# Create upload instance
				$uploader = new Upload($_FILES['lectureNotes'], $uploadDirectory);
								
				# Extensions allowed
				$uploader->setExtensions(array(".doc", ".docx", ".ppt", ".pptx", ".pdf")); 
				
				# Process upload
				$results = $uploader->upload();
				
				# Any errors?
				if($results['error'] == true) {
					
					# Redirect
					return $this->digitalUniversity->redirect('modules&module='.$module['code'].'&act=error&message='.serialize($results));
					
				} else {
					
					$fileName = $dateFolder.$results['filename'];
					
				}
				
				# Insert announcement			
				$this->digitalUniversity->db->query("INSERT INTO modules_notes SET moduleID = '{$module['moduleID']}', location = '{$fileName}', format = '{$results['extension']}', title = '{$this->digitalUniversity->post['title']}'");	
					
				# Redirect
				return $this->digitalUniversity->redirect('modules&module='.$module['code'].'&act=saved&message=The lecture notes were added');	
			
			# Add new assignment	
			} elseif(isset($this->digitalUniversity->post['addAssignment'])) {
				
				if(!empty($this->digitalUniversity->post['title'])) {
				
					# Make timestamp
					$deadline = mktime($this->digitalUniversity->post['hour'], 0, 0, $this->digitalUniversity->post['month'], $this->digitalUniversity->post['day'], $this->digitalUniversity->post['year']);
									
					# Insert assignment			
					$this->digitalUniversity->db->query("INSERT INTO modules_assessment SET moduleID = '{$module['moduleID']}', available = '1', worth = '{$this->digitalUniversity->post['worth']}', mark = '{$this->digitalUniversity->post['marks']}', title = '{$this->digitalUniversity->post['title']}', deadline = '{$deadline}'");	
					
					# Add an announcement?
					if(isset($this->digitalUniversity->post['autoAddAnnouncement'])) {
					
						$time = time();							
						$title = $this->digitalUniversity->post['title'].' is now available.';
						$this->digitalUniversity->db->query("INSERT INTO modules_news SET moduleID = '{$module['moduleID']}', title = '{$title}', status = '1', time = '{$time}'");	
										
					}
					
					# Send out notification
					$this->digitalUniversity->db->query("UPDATE users SET notifications = (notifications + 1) 
					WHERE userID IN (
						SELECT userID FROM users_modules WHERE moduleID = '{$module['moduleID']}'
					)");
					
					# Redirect
					return $this->digitalUniversity->redirect('modules&module='.$module['code'].'&act=saved&message=The assignment has been created');
				
				}
						
			}
			
		} 
						
		echo '<section class="leftColumn">
			<h1>'.(!empty($module['title']) ? $module['code'].': '.$module['title'] : 'Module').'</h1>
			<nav class="pageTab">
				<a class="focus" href="#" data-tab="resources">Resources</a>
				<a href="#" data-tab="details">Details</a>
				'.(($this->digitalUniversity->user['groupLevel'] != 3) ? '<a href="#" data-tab="assessment">Assessment</a>' : '').'
				'.($canAdministrate ? '<a href="#" data-tab="administrate">Administrate</a>' : '').'
			</nav>';
			
			# Administrate - only for lecturers and admins
			if($canAdministrate) {
			
				$this->adminModule(&$module);
				
			}
			
			echo '<!-- Open:tab_resources -->
			<section id="tab_resources" class="dataTab">';
			
			if(!empty($this->digitalUniversity->input['act'])) {
				
				if($this->digitalUniversity->input['act'] == 'saved') {
					
					echo '<p class="noticeBox"><strong>Success:</strong> '.(!empty($this->digitalUniversity->input['message']) ? $this->digitalUniversity->input['message'] : 'Your resource has been saved and is pending review!').'</p>';
						
				} elseif($this->digitalUniversity->input['act'] == 'error') {
					
					echo '<p class="noticeBox"><strong>Warning:</strong> An error occurred while saving the resource.</p>';
						
				}
				
			}
			
			if(!empty($module)) {
								
				if(!empty($moduleNotes)) {
									
					echo '<section class="contentBlock clearfix">
						<h2>Latest Lecture Notes</h2>';
											
					foreach($moduleNotes as $k => $v) {
							
						echo '<a href="'.$this->digitalUniversity->config['root_url'].'uploads/'.$v['location'].'" target="_blank">
							<article class="document pdf">							
								<h5 class="title">'.$v['title'].'</h5>
							</article>
						</a>';
								
					}
																						 
					echo '<a href="'.$this->digitalUniversity->config['scripturl'].'page=modules&module='.$module['code'].'&view=resources" class="viewMore">View More</a>
					</section>';
					
				}
								
			} else {
				
				echo '<h2>This module does not exist.</h2>';	
				
			}
			
			# Resources
			echo '<section class="contentBlock clearfix">
			<h2>Latest Resources</h2>';
					
			if(!empty($moduleResources)) {
								
				foreach($moduleResources as $k => $v) {
				
					if($v['type'] == 'book') {
						$link = 	$this->digitalUniversity->config['scripturl'].'page=books&book='.$v['resourceID'];
					} else {
						$link = 	$this->digitalUniversity->config['scripturl'].'page=resources&resource='.$v['resourceID'];
					}
					
					if($v['type'] == 'webpage') {
						$saveLink = $v['location'];
					} else {
						$saveLink = $this->digitalUniversity->config['root_url'].'uploads/'.$v['location'];
					}
				
					echo '
					<article class="document '.$v['type'].'">	
						<a href="'.$link.'" class="fillLink">						
							<h5 class="title">'.$v['title'].'</h5>
						</a>'.(($v['type'] != 'book') ? '
						<div class="documentControlContainer">
							<div class="dialog documentControl">
								<a class="save" href="'.$saveLink.'" target="_blank">Save</a>
								<a class="open" href="'.$link.'">Open</a>
							</div>
						</div>' : '').'
					</article>';
					
				}
				
				echo '<a href="'.$this->digitalUniversity->config['scripturl'].'page=modules&module='.$module['code'].'&view=resources" class="viewMore">View More</a>';
								
			} else {
				
				echo '<p>This module has no resources available.</p>';
				
			}			
		
			echo '</section>				
			</section>
			<!-- Close:tab_resources -->
			
			<!-- Open:tab_details -->
			<section id="tab_details" class="dataTab hidden">
				<section class="contentBlock moduleDetails">';
				
				if(!empty($moduleDetails)) {
										
					foreach($moduleDetails as $k => $v) {
					
						# Overview tab
						if($k == 'overview') {
					
							echo '<table>';
							
							# Loop through mini-details
							foreach($v as $ck => $cv) {
					
								if($ck == 'member_of_staff_with_responsibility_for_the_module') {
									$cv = 'staff_member';
								}
					
								# Friendly text key
								$key = ucfirst(str_replace('_', ' ', $ck));
									
								# Skip empty keys
								if(empty($cv)) {
									continue;
								}
																
								# Replace links
								$cv = preg_replace('#/teaching/modules/year([0-9])s([0-9])/([a-zA-Z0-9_-]*)\.html#e', '$this->digitalUniversity->config["scripturl"]."page=modules&module=".strtoupper("$3")', $cv);
							
								# Output contents
								echo '<tr>
									<td>'.$key.'</td>
									<td>'.$cv.'</td>
								</tr>';
							
							}
							
							echo '</table>';
						
						} else {
						
							if(empty($v)) {
								continue;
							}
						
							# Friendly text key
							$key = ucfirst(str_replace('_', ' ', $k));
							
							# Output details
							echo '<h4>'.$key.'</h4>';
							echo $v;							
							
						}
						
					}
					
				} else {
				
					echo '<p>There were no details found for this module.</p>';
					
				}
				
				echo '</section>
			</section>
			<!-- Close:tab_details -->
			
			<!-- Open:tab_assessment -->
			<section id="tab_assessment" class="dataTab hidden">';
				
				if(!empty($module)) {
					
					$this->moduleAssessments($module['moduleID']);
					
				} else {
				
					echo '<p>There were no details found for this module.</p>';
					
				}
				
			echo '</section>
			<!-- Close:tab_assessment -->
			
		</section>	';
		
		$this->showModuleSide($module);
		
	}
		
	/*
	 * outputPage: Detect the current page being viewed and output the relevant
	 * page contents
	*/
	public function outputPage() {
		
		# Page tree
		$this->digitalUniversity->addPageTree('Modules', $this->digitalUniversity->config['scripturl'].'page=modules');
		
		# View single module
		if(isset($this->digitalUniversity->post['save'])) {
			
			return $this->saveResource();
			
		} elseif(isset($this->digitalUniversity->input['module'])) {
			
			if(!empty($this->digitalUniversity->input['view'])) {
				
				if($this->digitalUniversity->input['view'] == 'resources') {
				
					return $this->viewModuleResources();	
				
				} elseif($this->digitalUniversity->input['view'] == 'new') {
					
					return $this->addNewResource();
					
				}
				
			} 
			
			return $this->showModule();
			
		}
		
		# Search page
		if(!empty($this->digitalUniversity->input['act']) && ($this->digitalUniversity->input['act'] == 'search') && !empty($this->digitalUniversity->post['keyword'])) {				
			$isSearch = true;	
			$searchPart[] = "title LIKE '%{$this->digitalUniversity->post['keyword']}%'";			
		} else {
			$isSearch = false;
		}
		
		# Query user modules
		if(!$isSearch) {
			
			$yourModules = $this->digitalUniversity->db->getResults("SELECT * FROM users_modules um 
			LEFT JOIN modules m ON (m.moduleID = um.moduleID)
			WHERE um.userID = '{$this->digitalUniversity->user['userID']}'
			LIMIT 8");
			
			$yourModuleContent = '';
			$moduleList = '';
			$moduleListArray = array();
			$searchPart = array();
			
			if(!empty($yourModules)) {
				foreach($yourModules as $k => $v) {
					if(($k+1) % 7 == 0) {
						$class = ' lastChild';
					} else {
						$class = '';
					}
					$yourModuleContent .= '<a href="'.$this->digitalUniversity->config['scripturl'].'page=modules&module='.$v['code'].'">
						<article class="document module'.$class.'">
							<h5 class="title">'.$v['code'].' - '.$v['title'].'</h5>
						</article>
					</a>';
					$moduleListArray[] = $v['moduleID'];
				}
			}
			
			if(!empty($moduleListArray)) {
				$moduleList = "'".implode("', '", $moduleListArray)."'";
			}
			
		}
			
		# Module list
		if(!empty($moduleList)) {
			$searchPart[] = "moduleID NOT IN({$moduleList})";
		}
								
		# Get other modules
		$modules = $this->digitalUniversity->db->getResults("SELECT * FROM modules 
		".(!empty($searchPart) ? "WHERE ".implode(' AND ', $searchPart) : '')."
		ORDER BY RAND()
		LIMIT 8");
				
		echo '
		<section class="fullPageWidth">
			<h1>Modules</h1>
			<nav class="pageTab">
				<a class="focus" href="#" data-tab="home">Your Modules</a>								
				<a href="#" data-tab="search">Search</a>
				<a class="right" href="'.$this->digitalUniversity->config['scripturl'].'page=resources" data-tab="notabber">Resources</a>
				<a class="right" href="'.$this->digitalUniversity->config['scripturl'].'page=book" data-tab="notabber">Books</a>
			</nav>
			
			<!-- Open: tab_search -->
			<section id="tab_search" class="dataTab'.(!$isSearch ? ' hidden' : '').'">
				<section class="contentBlock clearfix addNewResource">
					<form action="'.$this->digitalUniversity->config['scripturl'].'page=modules&act=search" method="post">
					<p class="noUpper">
						<label for="keyword">Keyword:</label> <input type="text" value="'.(!empty($this->digitalUniversity->post['keyword']) ? $this->digitalUniversity->post['keyword'] : '').'" id="keyword" name="keyword" />
					</p>
					<input type="submit" class="submitButton" name="searchResources" value="Search" />
				</form>				
				</section>
			</section>
			<!-- Close: tab_search -->
			
			<section id="tab_home" class="dataTab">';
			
				# Search page
				if($isSearch && empty($modules)) {								
					echo '<p class="noticeBox"><strong>Search:</strong> Your search returned no results.</p>';				
				}
						
				# Do we have any modules?
				if(!empty($yourModuleContent)) {
					
					echo '<section class="contentBlock clearfix">'.$yourModuleContent.'</section>';
					
				}				
																	
				# Are we lending anything?
				if(!empty($modules)) {
				
					echo '<section class="contentBlock clearfix">
					<h2>Other Modules</h2>';
					
					foreach($modules as $k => $v) {
																				
						if(($k+1) % 7 == 0) {
							$class = ' lastChild';
						} else {
							$class = '';
						}
						
						echo '
						<a href="'.$this->digitalUniversity->config['scripturl'].'page=modules&module='.$v['code'].'">
							<article class="document module'.$class.'">
								<h5 class="title">'.$v['code'].' - '.$v['title'].'</h5>
							</article>
						</a>';
							
					}
														 
					echo '</section>';
				
				}
				
			echo '</section>												
		</section>';
										
	}
		
}

?>